package com.jz.yanshe.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jz.jd.rest.response.OrderResponse;
import com.jz.yanshe.base.BaseActivity;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.qrcode.QRCodeReader;

import com.jz.yanshe.R;

import com.jz.yanshe.util.ImageLoaderHelper;
import com.jz.jd.rest.business.RestProxy;
import com.jz.jd.rest.exception.BusinessException;
import com.jz.jd.rest.response.AddressResponse;
import com.jz.jd.rest.response.BaseResponse;
import com.jz.jd.rest.response.ExpressPriceResponse;
import com.jz.jd.rest.response.ShoppingCarListResponse;
import com.jz.jd.rest.response.VIPBalanceResponse;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import com.jz.yanshe.util.PreferencesHelper;

/**
 * Created by Administrator on 2018/3/7.
 */

public class BuyActivity extends BaseActivity {
    List<ShoppingCarListResponse.ShoppingCar> list;

    @BindView(R.id.tv_user_address)
    TextView tv_user_address;

    @BindView(R.id.tv_user_phone)
    TextView tv_user_phone;

    @BindView(R.id.tv_user_name)
    TextView tv_user_name;

    @BindView(R.id.tv_price)
    TextView tv_price;

    @BindView(R.id.tv_order_price)
    TextView tv_order_price;

    @BindView(R.id.tv_balance)
    TextView tv_balance;

    @BindView(R.id.tv_pay)
    TextView tv_pay;

    @BindView(R.id.tv_pay_price)
    TextView tv_pay_price;


    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;


//    @BindView(R.id.tv_bank_num)
//    TextView tv_bank_num;

    @BindView(R.id.tv_express_price)
    TextView tv_express_price;

//    @BindView(R.id.img_alipay)
//    ImageView img_alipay;
//
//    @BindView(R.id.img_wechat)
//    ImageView img_wechat;

    MyAdapter myAdapter = new MyAdapter();

    double balance;
    double price;
    double express_price = 8;

    int logistics_type;

    @Override
    protected void initViews() {
        recyclerView.setAdapter(myAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = 2;
            }
        });
    }

    @Override
    protected void initData() {
        getAddress();
        getBalance();
        getPrice();
//        getWeChat();
//        getAliPayUrl();
        list = (ArrayList<ShoppingCarListResponse.ShoppingCar>) getIntent().getSerializableExtra("list");
        int num = 0;
        for (int i = 0; i < list.size(); i++) {
            price = price + Integer.valueOf(list.get(i).goods_num) * Double.valueOf(list.get(i).goods_price);
            num = num + Integer.valueOf(list.get(i).goods_num);
        }
        tv_price.setText("共" + num + "件商品   ¥" + price + " ");
        tv_order_price.setText("¥" + String.format("%.2f", Double.valueOf(price)));
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_buy;
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {


        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_buy, parent, false));
            return holder;
        }

        @Override
        public void onBindViewHolder(final Holder holder, final int position) {
            ImageLoaderHelper.getInstance().GlideImageLoader(BuyActivity.this, list.get(position).goods_icon, holder.img_goods);
            holder.tv_goods_name.setText(list.get(position).goods_name);
            holder.tv_goods_num.setText("x " + list.get(position).goods_num);
            holder.tv_goods_size.setText(list.get(position).style_color + "     " + list.get(position).style_size + "码");
            holder.tv_price.setText("¥ " + list.get(position).goods_price);
            holder.tv_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            holder.tv_price_now.setText("¥ " + list.get(position).goods_price);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {
            ImageView img_goods;
            TextView tv_goods_size, tv_goods_name, tv_goods_num, tv_price, tv_price_now;

            public Holder(View itemView) {
                super(itemView);
                img_goods = itemView.findViewById(R.id.img_goods);
                tv_goods_size = itemView.findViewById(R.id.tv_goods_size);
                tv_goods_name = itemView.findViewById(R.id.tv_goods_name);
                tv_goods_num = itemView.findViewById(R.id.tv_goods_num);
                tv_price = itemView.findViewById(R.id.tv_price);
                tv_price_now = itemView.findViewById(R.id.tv_price_now);
            }
        }
    }

    @OnClick(R.id.btn_confirm)
    void btn_confirm() {
        doOrder();
    }

    private void doOrder() {
        if (logistics_type != 1 && logistics_type != 2) {
            Toast.makeText(this, "请选择地址", Toast.LENGTH_SHORT).show();
            return;
        }

        RestProxy.getInstance().doOrder(PreferencesHelper.getInstance().getString(BuyActivity.this, "token"), tv_user_phone.getText().toString(), tv_user_name.getText().toString(), tv_user_address.getText().toString(), "2", logistics_type + "", list, new Observer<OrderResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(OrderResponse orderListResponse) {
//                Toast.makeText(BuyActivity.this, "下单成功", Toast.LENGTH_SHORT).show();
//                Bundle bundle = new Bundle();
//                double pay = price - balance;
//                if (pay > 0 || pay == 0) {
//                    bundle.putInt("id", 1);
//                } else {
//                    bundle.putInt("id", 2);
//                }
//
//                startActivity(MyOrderActivity.class, bundle);
                Bundle bundle = new Bundle();
                bundle.putString("orderid",orderListResponse.order.order_id);
                startActivity(AlipayActivity.class,bundle);
                finish();
            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof BusinessException) {
                    Toast.makeText(BuyActivity.this, ((BusinessException) e).errorDescription, Toast.LENGTH_SHORT).show();
                    toLogin(((BusinessException) e).errorCode);
                }
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @OnClick(R.id.btn_address)
    void btn_address() {
        Bundle bundle = new Bundle();
        bundle.putInt("id", 0);
        startActivityForResult(MyAddressActivity.class, bundle, 1);
    }

    private void getAddress() {
        RestProxy.getInstance().getDefaultAddress(PreferencesHelper.getInstance().getString(BuyActivity.this, "token"), new Observer<AddressResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(AddressResponse addressResponse) {
                tv_user_phone.setText(addressResponse.map.phone);
                tv_user_address.setText(addressResponse.map.address_all);
                tv_user_name.setText(addressResponse.map.nick_name);
            }

            @Override
            public void onError(Throwable e) {

                if (e instanceof BusinessException) {
                    toLogin(((BusinessException) e).errorCode);
                }
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        logistics_type = resultCode;
        if (resultCode == 1)
            if (requestCode == 1) {
                AddressResponse.Address address = (AddressResponse.Address) data.getSerializableExtra("obj");
                tv_user_phone.setText(address.phone);
                tv_user_address.setText(address.address_all);
                tv_user_name.setText(address.nick_name);
                tv_express_price.setText("¥" + express_price);
            }
        if (resultCode == 2) {
            AddressResponse.Address address = (AddressResponse.Address) data.getSerializableExtra("obj");
            tv_user_phone.setText(address.phone);
            tv_user_address.setText(address.address_all);
            tv_user_name.setText(address.nick_name);
            tv_express_price.setText("¥0");
        }
    }

//    @OnClick(R.id.btn_copy)
//    void btn_copy() {
//        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
//        ClipData mClipData = ClipData.newPlainText("Label", tv_bank_num.getText().toString());
//// 将ClipData内容放到系统剪贴板里。
//        cm.setPrimaryClip(mClipData);
//        Toast.makeText(this, "复制成功", Toast.LENGTH_SHORT).show();
//    }

    private void getBalance() {
        RestProxy.getInstance().getVIPBalance(PreferencesHelper.getInstance().getString(this, "token"), new Observer<VIPBalanceResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(VIPBalanceResponse vipBalanceResponse) {
                balance = vipBalanceResponse.balance;
                tv_balance.setText("-¥" + String.format("%.2f", balance));
                double pay = price - balance + express_price;
                if (pay > 0 || pay == 0) {
                    tv_pay.setText("应付 ¥" + String.format("%.2f", pay));
                } else {
                    tv_pay.setText("应付 ¥0.00");
                }

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void getPrice() {
        RestProxy.getInstance().getExpressPrice(new Observer<ExpressPriceResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ExpressPriceResponse expressPriceResponse) {
                express_price = Double.valueOf(expressPriceResponse.entity.common_configuration_description);
                tv_express_price.setText("¥" + expressPriceResponse.entity.common_configuration_description);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

//    private void getAliPayUrl() {
//        RestProxy.getInstance().getAliPayUrl(new Observer<ExpressPriceResponse>() {
//            @Override
//            public void onSubscribe(Disposable d) {
//
//            }
//
//            @Override
//            public void onNext(ExpressPriceResponse expressPriceResponse) {
//                ImageLoaderHelper.getInstance().GlideImageLoader(BuyActivity.this, expressPriceResponse.entity.common_configuration_description, img_alipay);
//            }
//
//            @Override
//            public void onError(Throwable e) {
//
//            }
//
//            @Override
//            public void onComplete() {
//
//            }
//        });
//    }
//
//
//    private void getWeChat() {
//        RestProxy.getInstance().getWeChatUrl(new Observer<ExpressPriceResponse>() {
//            @Override
//            public void onSubscribe(Disposable d) {
//
//            }
//
//            @Override
//            public void onNext(ExpressPriceResponse expressPriceResponse) {
//                ImageLoaderHelper.getInstance().GlideImageLoader(BuyActivity.this, expressPriceResponse.entity.common_configuration_description, img_wechat);
//            }
//
//            @Override
//            public void onError(Throwable e) {
//
//            }
//
//            @Override
//            public void onComplete() {
//
//            }
//        });
//    }
//
//
//    @OnLongClick(R.id.img_alipay)
//    boolean img_alipay() {
//        Bitmap obmp = ((BitmapDrawable) (img_alipay.getDrawable())).getBitmap();
//        int width = obmp.getWidth();
//        int height = obmp.getHeight();
//        int[] data = new int[width * height];
//        obmp.getPixels(data, 0, width, 0, 0, width, height);
//        RGBLuminanceSource source = new RGBLuminanceSource(width, height, data);
//        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
//        new QrCodeAsyncTask().execute(bitmap);
//        return true;
//    }
//
//
//    @OnLongClick(R.id.img_wechat)
//    boolean img_wechat() {
//        new Handler().postDelayed(new Runnable() {
//
//            @Override
//            public void run() {
//                // 要在运行在子线程中
//                Bitmap obmp = ((BitmapDrawable) (img_wechat.getDrawable())).getBitmap();
//                savePicture(obmp, System.currentTimeMillis()+".jpg");// 保存图片
//                img_wechat.destroyDrawingCache(); // 保存过后释放资源
//            }
//        },100);
//        return true;
//    }

    public void savePicture(Bitmap bm, String fileName) {
        verifyStoragePermissions(this);

        Log.i("xing", "savePicture: ------------------------");
        if (null == bm) {
            Log.i("xing", "savePicture: ------------------图片为空------");
            return;
        }
        File foder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test");
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(foder, fileName);
        try {
            if (!myCaptureFile.exists()) {
                myCaptureFile.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            //压缩保存到本地
            bm.compress(Bitmap.CompressFormat.JPEG, 90, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "权限不足!", Toast.LENGTH_SHORT).show();
            return;
        }
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myCaptureFile)));
        Toast.makeText(this, "保存成功!", Toast.LENGTH_SHORT).show();
    }

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    public void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }


    class QrCodeAsyncTask extends AsyncTask<BinaryBitmap, Void, Result> {

        @Override
        protected Result doInBackground(BinaryBitmap... params) {
            QRCodeReader reader = new QRCodeReader();
            Result result = null;
            try {
                result = reader.decode(params[0]);
            } catch (NotFoundException e) {
                e.printStackTrace();
            } catch (ChecksumException e) {
                e.printStackTrace();
            } catch (FormatException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(Result result) {
            super.onPostExecute(result);

            String text = result.getText();
//            Logger.info(TAG, "QR CODE: " + text);
            Toast.makeText(BuyActivity.this, "正在跳转..", Toast.LENGTH_SHORT).show();
            Bundle bundle = new Bundle();
            bundle.putString("url", text);

            startActivity(WebViewActivity.class, bundle);
        }

    }
}
